package edu.iit.cs553;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.ec2.AmazonEC2Client;
import com.amazonaws.services.ec2.model.StopInstancesRequest;

public class Worker {

	private HttpClient client;
	private AmazonEC2Client amazonEC2Client;

	public Worker()
	{
		this.client = new DefaultHttpClient();
		BasicAWSCredentials credentials = new BasicAWSCredentials("", "");
		this.amazonEC2Client = new AmazonEC2Client(credentials);
		amazonEC2Client.setEndpoint("ec2.us-west-2.amazonaws.com");
	}

	public void stopInstance() throws ClientProtocolException, IOException
	{
		String instanceId = getInstanceId();
		List<String> instancesId = new ArrayList<String>();
		instancesId.add(instanceId);
		StopInstancesRequest stopInstancesRequest = new StopInstancesRequest(instancesId);
		amazonEC2Client.stopInstances(stopInstancesRequest);
	}

	private String getInstanceId() throws ClientProtocolException, IOException
	{
		HttpGet request = new HttpGet("http://169.254.169.254/latest/meta-data/instance-id");
		HttpResponse response = client.execute(request);
		HttpEntity entity = response.getEntity();
		InputStream is = entity.getContent();
		String instanceId = IOUtils.toString(is);
		return instanceId;
	}
}
